package cn.bincker.web.blog.base.controller;

import cn.bincker.web.blog.base.annotation.ApiController;
import cn.bincker.web.blog.base.entity.FriendLink;
import cn.bincker.web.blog.base.service.IFriendLinkService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.Pattern;
import java.util.List;

import static cn.bincker.web.blog.base.constant.RegexpConstant.STATION_URL_VALUE;
import static cn.bincker.web.blog.base.constant.RegexpConstant.TITLE_HTML_TAG;

@ApiController
@RestController
@RequestMapping("friend-link")
public class FriendLinkController {
    private final IFriendLinkService friendLinkService;
    private final RestTemplate restTemplate;

    public FriendLinkController(IFriendLinkService friendLinkService, RestTemplate restTemplate) {
        this.friendLinkService = friendLinkService;
        this.restTemplate = restTemplate;
    }

    @GetMapping
    public Page<FriendLink> page(String keywords, FriendLink.Status status, Pageable pageable){
        return friendLinkService.page(keywords, status, pageable);
    }

    @GetMapping("all")
    public List<FriendLink> all(){
        return friendLinkService.list();
    }

    @PostMapping
    public FriendLink add(@Validated @RequestBody FriendLink friendLink){
        return friendLinkService.add(friendLink);
    }

    @PutMapping
    public FriendLink update(@Validated @RequestBody FriendLink friendLink){
        return friendLinkService.update(friendLink);
    }

    @DeleteMapping("{id}")
    public void delete(@PathVariable Long id){
        friendLinkService.delete(id);
    }

    @GetMapping("/station-title")
    public String getStationTitle(@Validated @Pattern(regexp = STATION_URL_VALUE) String url){
        var html = restTemplate.getForObject(url, String.class);
        if(html == null) return "";
        var matcher = TITLE_HTML_TAG.matcher(html);
        if(!matcher.find()) return "";
        return matcher.group(1);
    }
}
